﻿using CleanArchitecture.Core;
using CleanArchitecture.Core.Configuration;
using CleanArchitecture.Core.Interfaces;
using CleanArchitecture.Core.Interfaces.Cache;
using CleanArchitecture.Infrastructure.Entities;
using CleanArchitecture.Infrastructure.Entities.Business;
using CleanArchitecture.Infrastructure.Entities.Settings;
using CleanArchitecture.Infrastructure.Interfaces;
using Microsoft.AspNetCore.Http;
using Qiniu.Http;
using Qiniu.Storage;
using Qiniu.Util;
using System.IO;
using System.Threading.Tasks;

namespace CleanArchitecture.Infrastructure.Services.Media
{
    //public partial class QiniuPictureService : PictureService
    //{
    //    #region Fields
    //    private readonly IStaticCacheManager _cacheManager;
    //    private readonly MediaSettings _mediaSettings;
    //    private readonly object _locker = new object();
    //    private readonly IDomainEventDispatcher _eventDispatcher;

    //    private static string _qiniuAuthToken;
    //    private static string _qiniuaccessKey;
    //    private static string _qiniusecretKey;
    //    private static string _qiniubucketName;
    //    private static string _qiniudomainName;
    //    private static int _qiniuUploadExpire;
    //    private static string _qiniuUploadZone;

    //    private HttpResult _requestResult;
    //    private readonly IRepository<Picture> _pictureRepository;
    //    #endregion

    //    #region Ctor

    //    public QiniuPictureService(IDataProvider dataProvider,
    //        IDbContext dbContext,
    //        IDomainEventDispatcher eventDispatcher,
    //        IHttpContextAccessor httpContextAccessor,
    //        INowaFileProvider fileProvider,
    //        IRepository<Picture> pictureRepository,
    //        IRepository<PictureBinary> pictureBinaryRepository,
    //        ISettingService settingService,
    //        IStaticCacheManager cacheManager,
    //        IWebHelper webHelper,
    //        MediaSettings mediaSettings,
    //        NowaConfig config)
    //        : base(dataProvider,
    //              dbContext,
    //              eventDispatcher,
    //              httpContextAccessor,
    //              fileProvider,
    //              pictureRepository,
    //              pictureBinaryRepository,
    //              webHelper,
    //              mediaSettings,
    //              settingService)
    //    {
    //        _cacheManager = cacheManager;
    //        _mediaSettings = mediaSettings;
    //        _pictureRepository = pictureRepository;
    //        _eventDispatcher = eventDispatcher;
    //        OneTimeInit(config);
    //    }
    //    #endregion

    //    #region Utilities

    //    protected void OneTimeInit(NowaConfig config)
    //    {
    //        if (!string.IsNullOrEmpty(_qiniuAuthToken))
    //            return;

    //        if (string.IsNullOrEmpty(config.QiniuAccessKey)
    //         || string.IsNullOrEmpty(config.QiniuSecretKey)
    //         || string.IsNullOrEmpty(config.QiniuBucketName)
    //         || string.IsNullOrEmpty(config.QiniuDomain))
    //            throw new NowaException("Qiniu Cloud Config for Storage is not specified");
            
    //        lock (_locker)
    //        {
    //            if (!string.IsNullOrEmpty(_qiniuAuthToken))
    //                return;

    //            _qiniuaccessKey = config.QiniuAccessKey;
    //            _qiniusecretKey = config.QiniuSecretKey;
    //            _qiniubucketName = config.QiniuBucketName.Trim();
    //            _qiniudomainName = config.QiniuDomain.Trim().ToLower().TrimEnd('/');
    //            _qiniuUploadExpire = config.QiniuUploadExpire;
    //            _qiniuUploadZone = config.QiniuUploadZone;
    //            _qiniuAuthToken = CreateQiniuAuthToken();
    //        }
    //    }

    //    private string CreateQiniuAuthToken()
    //    {
    //        Mac mac = new Mac(_qiniuaccessKey, _qiniusecretKey);
    //        PutPolicy putPolicy = new PutPolicy();
    //        putPolicy.Scope = _qiniubucketName;
    //        putPolicy.SetExpires(_qiniuUploadExpire);
    //        putPolicy.ReturnBody = "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"fsize\":$(fsize),\"bucket\":\"$(bucket)\",\"name\":\"$(x:name)\"}";
    //        return Auth.CreateUploadToken(mac, putPolicy.ToJsonString());
    //    }
    //    #endregion

    //    #region Method
    //    public override Stream GetCloudImageStream(string url, string defaultImgPath)
    //    {
    //        if (_requestResult == null)
    //            LoadCloudImage(url).Wait();

    //        Stream imageStream;
    //        if (_requestResult.Code != (int)HttpCode.OK)
    //        {
    //            Picture entity = new Picture()
    //            {
    //                SysLogLvl = SystemLogLevel.Error,
    //                SysLogMsg = $"Qiniu Http Request Error: Code:{_requestResult.Code}, Message: {_requestResult.Text}"
    //            };
    //            _eventDispatcher.Dispatch(new QiniuCloudHttpEvent(entity));
    //            //Load Default image if image not found
    //            return base.GetCloudImageStream(string.Empty, defaultImgPath);
    //        }
    //        else imageStream = new MemoryStream(_requestResult.Data);
    //        _requestResult = null;
    //        return imageStream;
    //    }

    //    private async Task LoadCloudImage(string url)
    //    {
    //        HttpManager qiniuHttp = new HttpManager(false);
    //        _requestResult = qiniuHttp.Get(url, null, true);
    //    }

    //    /// <summary>
    //    /// DavidLee 2019/12/13 增加对云端上传功能的匹配
    //    /// </summary>
    //    public override void UploadImg2Cloud(Picture imgEntity)
    //    {
    //        if(imgEntity.StoreType == EntityEnumConfig.FileStoreType.LocalStorage)
    //        {
    //            UploadImageData2Cloud(imgEntity).Wait();
    //            if (_requestResult.Code != (int)HttpCode.OK)
    //            {//如上传不成功，则日志记录，并改为本地存储
    //                imgEntity.SysLogLvl = SystemLogLevel.Error;
    //                imgEntity.SysLogMsg = $"Qiniu Http Upload Error: PictureId: {imgEntity.Id}, Code:{_requestResult.Code}, Message: {_requestResult.Text}";
    //                _eventDispatcher.Dispatch(new QiniuCloudHttpEvent(imgEntity));
    //                _requestResult = null;
    //                return;
    //            }
    //            imgEntity.StoreType = EntityEnumConfig.FileStoreType.QiniuCloud;
    //            imgEntity.IsNew = EntityEnumConfig.YesorNo.No;
    //            _pictureRepository.Update(imgEntity);
    //        }
    //        _requestResult = null;
    //    }

    //    private async Task UploadImageData2Cloud(Picture picture)
    //    {
    //        var uploadData = LoadPictureBinary(picture, StoreInDb);
    //        Config config = new Config();
    //        // 设置上传区域
    //        config.Zone = GetQiniuUploadZone();
    //        // 设置 http 或者 https 上传
    //        config.UseHttps = true;
    //        config.UseCdnDomains = true;
    //        config.ChunkSize = ChunkUnit.U512K;
    //        PutExtra extra = new PutExtra()
    //        {
    //            MimeType = picture.MimeType
    //        };
    //        string fileName = picture.VirtualPath.TrimStart('~').TrimStart('/') + "/" + picture.SeoFilename + "." + GetFileExtensionFromMimeType(picture.MimeType);
    //        // 表单上传
    //        UploadManager manager = new UploadManager(config);
    //        _requestResult = manager.UploadData(uploadData, fileName, _qiniuAuthToken, extra);
    //    }

    //    private Zone GetQiniuUploadZone()
    //    {
    //        string uploadZone = string.IsNullOrEmpty(_qiniuUploadZone)
    //                          ? "ZONE_CN_South"
    //                          : _qiniuUploadZone;
    //        switch(uploadZone)
    //        {
    //            case "ZONE_CN_East":
    //                return Zone.ZONE_CN_East;
    //            case "ZONE_CN_North":
    //                return Zone.ZONE_CN_North;
    //            case "ZONE_CN_South":
    //                return Zone.ZONE_CN_South;
    //            case "ZONE_US_North":
    //                return Zone.ZONE_US_North;
    //            case "ZONE_AS_Singapore":
    //                return Zone.ZONE_AS_Singapore;
    //            default:
    //                return Zone.ZONE_CN_South;
    //        }
    //    }
    //    #endregion Method
    //}
}
